
import { ecsclass, EcsComponent, EcsEntity } from 'db://pkg/@gamex/cc-ecs';

@ecsclass('TimerComponent')
export class TimerComponent extends EcsComponent<EcsEntity> {
    static allowRecycling = true;
    protected onDisable() {
        this.timerID = 0;
        this.callbacks.clear();
        this.finishCallbacks.length = 0;
    }

    /**
     * timerID
     */
    private timerID = 0;
    /**
     * 定时回调
     */
    private callbacks: Map<number, { time: number, callback: Function }> = new Map();
    /**
     * 全局回调
     */
    private finishCallbacks: Function[] = [];

    /**
     * 添加定时器
     * (注意: 如果Timer组件被提前销毁，callback不会被调用)
     */
    public addTimer(time: number, callback?: Function) {
        this.callbacks.set(++this.timerID, { time: time || 0, callback: callback });
        return this.timerID;
    }

    /**
     * 移除定时器
     */
    public removeTimer(timerID: number) {
        return this.callbacks.delete(timerID);
    }

    /**
     * 全部完成回调
     * (注意: 如果Timer组件被提前销毁，finish不会被调用)
     */
    public onFinish(callback: Function) {
        this.finishCallbacks.push(callback);
    }

    /**************************以下为系统调用**************************/
    static systemExecute(timer: TimerComponent, dt: number) {
        const splices: number[] = [];
        timer.callbacks.forEach((data, id) => {
            data.time -= dt;
            if (data.time <= 0) {
                splices.push(id);
                data.callback && data.callback();
            }
        });

        splices.forEach((id) => {
            timer.callbacks.delete(id);
        });

        if (timer.callbacks.size === 0) {
            timer.finishCallbacks.forEach(finishs => finishs());
        }

        return timer.callbacks.size;
    }
}